<template>
  <div class="register">
    <div class="title">湖北省综合运输研究会后台系统</div>
    <el-form class="form" :model="registerUser" label-width="84px">
      <el-form-item
        label="账户"
        prop="username"
        :rules="[
          {
            required: true,
            message: '请输入账户',
          },
        ]"
      >
        <el-input v-model="registerUser.username" />
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password1"
        :rules="[
          {
            required: true,
            message: '请输入密码',
          },
        ]"
      >
        <el-input type="password" v-model="registerUser.password1" />
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="password2"
        :rules="[
          {
            required: true,
            message: '请输入第二次密码',
          },
        ]"
      >
        <el-input type="password" v-model="registerUser.password2" />
      </el-form-item>
      <div class="row center">
        <el-button type="primary" @click="register">注册</el-button>
        <el-button @click="login">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { useUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { error } from 'console'

const userStore = useUserStore()
const router = useRouter()

const registerUser = ref({
  username: '',
  password1: '',
  password2: '',
})

const register = () => {
  if (
    registerUser.value.username === '' ||
    registerUser.value.password1 === '' ||
    registerUser.value.password2 === ''
  ) {
    ElMessage({
      message: '账户或密码为空',
      type: 'error',
    })
    return
  }
  if (registerUser.value.password1 !== registerUser.value.password2) {
    ElMessage({
      message: '输入的两次密码不一致',
      type: 'error',
    })
    return
  }
  axios
    .post('/api/register', {
      hbjtusername: registerUser.value.username,
      hbjtpassword: registerUser.value.password1,
    })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        userStore.token = res.data.token
        window.localStorage.setItem('token', res.data.token)
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        router.replace({
          name: 'admin',
        })
      }
    })
    .catch((error) => {
      ElMessage({
        message: '注册失败，可能已有该账户',
        type: 'error',
      })
    })
}

const login = () => {
  router.replace({
    name: 'login',
  })
}
</script>

<style scoped>
.register {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: linear-gradient(25deg, #006387, #0d8ea4, #0ebbc1, #00ebdf);
}
.title {
  font-size: xx-large;
  margin: 24vh 0 36px 0;
  color: white;
}
.form {
  background: white;
  padding: 48px 48px 24px 48px;
  border-radius: 10px;
}
</style>
